package logic

import (
	"context"
	"fmt"
	"library/library/internal/svc"
	"library/library/library"
	"library/models/cache"
	"library/models/mysql"
	"library/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *library.LoginRequest) (*library.LoginResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
	if get.Val() != in.Sms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var user mysql.User
	mysql.DB.Where("account = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("未注册的用户无法登录")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}

	return &library.LoginResponse{UserId: int64(user.ID)}, nil
}
